// component/ui/z-range-input/z-range-input.js
import {
  _isWhatType
} from '../common/utils';

const customFormControls = require('../common/custom-form-controls')
const formPath = '../z-form-popup/z-form-popup'
Component({
  behaviors: [customFormControls],
  relations: {
    [formPath]: {
      type: 'ancestor',
      linked(target) {},
      linkChanged(target) {},
      unlinked(target) {},
    },
  },

  /**
   * 组件的配置
   */
  options: {
    styleIsolation: 'isolated',
    pureDataPattern: /^_/,
  },

  /**
   * 组件的属性列表
   */
  properties: {
    value: {
      type: Object,
    },
    prop: {
      type: String,
      value: '',
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    _isFormCuttent: false,
    _min: '',
    _max: '',
    min: '',
    max: '',
  },

  /**
   * 组件的数据监听
   */
  observers: {
    value(val) {
      if (_isWhatType(val) === 'Object') {
        const {
          min = '',
            max = '',
        } = val
        this.data._isFormCuttent = true
        this.data._min = min
        this.data._max = max
        this.setData({
          min: min,
          max: max,
        })
      }
    }
  },

  /**
   * 组件的生命周期
   */
  lifetimes: {
    created() {
      Object.defineProperty(this, 'parent', {
        get: () => this.getRelationNodes(formPath)[0],
      });
    },
    attached() {},
    detached() {},
  },

  /**
   * 组件的方法列表
   */
  methods: {
    onMinInput(e) {
      const {
        prop
      } = this.data
      this.data._min = e.detail.value
      this.data._isFormCuttent = true
      this.parent && this.parent.onClear(this, prop)
    },
    onMaxInput(e) {
      const {
        prop
      } = this.data
      this.data._max = e.detail.value
      this.data._isFormCuttent = true
      this.parent && this.parent.onClear(this, prop)
    },
    validator() {
      const {
        _min,
        _max
      } = this.data
      if (!_max && _min) {
        return true
      }
      if (_min > _max) {
        wx.showToast({
          title: '输入有误，最大值不能小于最小值~',
          icon: 'none'
        })
        return false
      }
      return true
    },
    onClear() {
      this.data._isFormCuttent = false
      this.reset()
    },
    onConfirm() {
      const {
        prop,
        _min,
        _max,
        _isFormCuttent,
      } = this.data;
      if (!_isFormCuttent) return;
      (this.parent || {}).data._form[prop] = {
        min: _min,
        max: _max,
      };
      (this.parent || {}).data._label[prop] = `${_min}-${_max}`
    },

    onReset() {
      const {
        value
      } = this.data
      if (_isWhatType(value) === 'Object') {
        this.reset()
      }
    },

    reset() {
      this.data._min = ''
      this.data._max = ''
      this.setData({
        min: '',
        max: '',
      })
    }

  }
})